/**
 * 
 */
package com.nextive.interview.activity;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.nextive.interview.R;
import com.nextive.interview.dao.WeightInfoDao;
import com.nextive.interview.service.WeightInfoService;
import com.nextive.interview.service.impl.WeightInfoServiceImpl;

/**
 * @author Martin
 *
 */
public class EditWeightEntryActivity extends Activity {
	
	private Long weightEntryId;
	
	private EditText weightInput;
	private Button pickDateButton;
	private TextView dateDisplay;
	private Button confirmButton;
	
	private int year;
	private int month;
	private int day;
	private static final int DATE_DIALOG_ID = 0;
	
	private WeightInfoService weightInfoService;
	
	public EditWeightEntryActivity() {
		
		this.weightInfoService = new WeightInfoServiceImpl(this);
		
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.weight_edit);
		
		bindInputs();
		configurePickDateButton();
		configureConfirmButton();
		configureDateDisplay();
		
		
		
		weightEntryId = (savedInstanceState == null) ? null : 
			(Long) savedInstanceState.getSerializable(WeightInfoDao.ID_KEY);
		
		if (weightEntryId == null) {
			
			Bundle extras = getIntent().getExtras();
			if (extras != null)
				weightEntryId = (Long) extras.getSerializable(WeightInfoDao.ID_KEY);
			
		}
		
		// TODO - I removed this because it is being called from : onResume(). if not needed remove !
		//populateWeightInfo();
		
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, new OnDateSetListener() {
				
				@Override
				public void onDateSet(DatePicker view, int yearIn, int monthOfYear,
						int dayOfMonth) {

					year = yearIn;
					month = monthOfYear;
					day = dayOfMonth;
					updateDateDisplay();
					
				}
			}, year, month, day);
		}
		
		return null;
	}

	// TODO - Check if we have to save the entry if we didn't complete all fields.
	// in here, if we happen to close the app or exit the app we save a partial entry
	// what do we do then ? default date and default weight ?
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		
		super.onSaveInstanceState(outState);
		savePartialState();
		outState.putSerializable(WeightInfoDao.ID_KEY, weightEntryId);
	}
    
    @Override
	protected void onPause() {
    	
		super.onPause();
		savePartialState();
		
	}

	@Override
	protected void onResume() {
		super.onResume();
		populateWeightInfo();
	}

	private void savePartialState() {
    	
		String weightText = weightInput.getText().toString();
		String dateText = dateDisplay.getText().toString();
		
    	if (weightEntryId == null) {
    		
    		// create a new weight entry
    		// TODO - add parameters to save the actual entry !!!
    		weightEntryId = weightInfoService.createNewWeightEntry(weightText, dateText);
    		
    	} else {
    		
    		weightInfoService.updateWeightInfo(weightEntryId, weightText, dateText);
    		
    	}
    }
	
	private void populateWeightInfo() {
		
		if (weightEntryId != null) {
			
			Cursor cursor = weightInfoService.generateEditWeightHistoryCursor(weightEntryId);
			if (cursor != null) {
				
				startManagingCursor(cursor);
				weightInput.setText(cursor.getString(cursor.getColumnIndex(WeightInfoDao.WEIGHT_KEY)));
				
				//TODO - format the date maybe ???
				dateDisplay.setText(cursor.getString(cursor.getColumnIndex(WeightInfoDao.DATE_KEY)));
				
			}
			
		}
		
	}

	/**
	 * It binds all inputs to member fields so they can be referenced later on.
	 */
	private void bindInputs() {
		
		weightInput= (EditText) findViewById(R.id.weight);
		dateDisplay = (TextView) findViewById(R.id.dateDisplay);
		confirmButton = (Button) findViewById(R.id.confirm_edit);
		pickDateButton = (Button) findViewById(R.id.pickDate);
		
	}

	private void configureDateDisplay() {
		
		final Calendar calendar = Calendar.getInstance();
		year = calendar.get(Calendar.YEAR);
		month = calendar.get(Calendar.MONTH);
		day = calendar.get(Calendar.DAY_OF_MONTH);
		
		updateDateDisplay();
		
	}
	
	private void updateDateDisplay() {

		dateDisplay.setText(new StringBuilder()
		.append(month + 1).append("-")
		.append(day).append("-")
		.append(year).append(" "));

	}
	
	private void configureConfirmButton() {

		confirmButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
			
				// there is no need to save anything since is being handled by onPause()
				setResult(RESULT_OK);
				finish();
				
			}
		});

	}

	private void configurePickDateButton() {

		pickDateButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
			
				showDialog(DATE_DIALOG_ID);
				
			}
		});

	}

}
